<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="10"><el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList"></el-input></el-col>
        <el-col :span="1"><el-button icon="el-icon-search" @click="getUserList"></el-button></el-col>
        <el-col :span="4"><el-button type="primary" style="margin-left: 20px;" @click="addDialogVisible = true">添加用户</el-button></el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border strpe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽v-slot -->
          <template v-slot="scope">
            <!-- {{ scope.row }} -->
            <!-- switch @change 回调函数 -->
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <!-- 编辑按钮 -->
            <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="权限" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
    v-model="addDialogVisible"
    title="添加用户"
    width="50%"
    :before-close="handleClose" @close="addDialogClosed"
  >
  <!-- 内容主体区域 -->
  <el-form :model="addFrom" :rules="addFromRules" ref="addFromRef" label-width="70px">
  <el-form-item label="用户名" prop="username">
    <el-input v-model="addFrom.username"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input v-model="addFrom.password"></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="addFrom.email"></el-input>
  </el-form-item>
  <el-form-item label="手机" prop="mobile">
    <el-input v-model="addFrom.mobile"></el-input>
  </el-form-item>
  </el-form>
    <!-- 底部区域 -->
    <template #footer>
      <div >
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addUser">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 编辑用户对话框 -->
  <el-dialog
    v-model="editDialogVisible"
    title="编辑用户"
    width="50%"
    @close="editDialogClose"
  >
  <el-form
    ref="editFromRef"
    :model="editFrom"
    status-icon
    :rules="editFromRules"
    label-width="70px"
  >
    <el-form-item label="用户名" >
      <el-input v-model="editFrom.username" disabled/>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="editFrom.email"/>
    </el-form-item><el-form-item label="手机号" prop="mobile">
      <el-input v-model="editFrom.mobile"/>
    </el-form-item>
  </el-form>
    <template #footer>
      <div>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editUserInfo">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    const checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则
      const regEmail = /^([a-zA-Z0-9])+@([a-zA-z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    const checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 获取用户列表对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示的数据
        pagesize: 2
      },
      userlist: [],
      total: 0,
      // 添加用户的表单数据
      addFrom: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单规则对象
      addFromRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改用户表单的验证规则对象
      editFromRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 控制编辑用户对话框得显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editFrom: {}
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userlist = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    // 监听 pagesize 改变的值的事件
    handleSizeChange (newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听 switch 开关状态的改变
    async userStateChanged (userinfo) {
      // console.log(userinfo)
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('用户状态更新成功！')
    },
    // handleEdit (row) {
    //   console.log('编辑', row)
    // },
    // 添加用户的预校验
    addUser () {
      // this.addDialogVisible = false
      this.$refs.addFromRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return this.$message.error('检验未通过')
        const { data: res } = await this.$http.post('users', this.addFrom)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加成功')
        // 隐藏用户对话框
        this.addDialogVisible = false
        // 重新获取用户列表
        this.getUserList()
        // console.log(res)
        // this.$message.success('添加成功')
      })
    },
    // 监听添加用户对话框的关闭
    addDialogClosed () {
      this.$refs.addFromRef.resetFields()
    },
    // 监听修改用户对话框的关闭
    editDialogClose () {
      this.$refs.editFromRef.resetFields()
    },
    // 显示编辑用户得对话框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.editFrom = res.data
      this.editDialogVisible = true
      // console.log(res)
    },
    // 修改用户信息并提交
    editUserInfo () {
      // 表单预校验
      this.$refs.editFromRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        // 发起修改用户的请求
        const { data: res } = await this.$http.put('users/' + this.editFrom.id, {
          email: this.editFrom.email,
          mobile: this.editFrom.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败')
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 更新数据
        this.getUserList()
        // 提示成功
        this.$message.success('更新用户信息成功')
      })
    },
    // 根据id删除对应用户信息
    async removeUserById (id) {
      // console.log(id)
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如何用户确认删除则返回字符串 confirm
      // 如何用户确认删除则返回字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        this.$message.info('已取消删除')
      } else {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) {
          this.$message.error('删除用户失败!')
        }
        this.$message.success('删除用户成功!')
        this.getUserList()
      }
    }
  }
}
</script>
<style lang="less" scoped>
</style>
